<template>
  <div class="h100 column jcsb">
    <div>
      <!-- #region header -->
      <div class="row jcfe">
        <el-button size="default" type="primary" :icon="Plus" @click="onAdd">
          添加
        </el-button>
      </div>
      <!-- #endregion -->

      <!-- #region table -->

      <el-table
        v-loading="loading"
        :data="pesticides"
        max-height="520"
        stripe
        table-layout="fixed"
      >
        <el-table-column prop="name" label="产品名" />
        <!-- <el-table-column prop="registrationNumber" label="登记证号" /> -->
        <el-table-column prop="netContent" label="净含量" />

        <el-table-column label="创建时间">
          <template #default="scope">
            <span>{{ new Date(scope.row.createTime).toLocaleString() }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="380"
          align="center"
          header-align="center"
          class="mr-0"
        >
          <template #default="scope">
            <el-button type="default" icon="View" @click="onDetail(scope.row)"
              >详细</el-button
            >
            <el-button
              type="default"
              icon="CopyDocument"
              @click="onCopy(scope.row)"
              >复制</el-button
            >
            <el-button type="primary" icon="Edit" @click="onEdit(scope.row)">
              编辑
            </el-button>
            <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="否"
              icon="WarningFilled"
              icon-color="#E6A23C"
              title="二维码对应的页面将无法显示，是否确定?"
              @confirm="onDelete(scope.row.id)"
              width="300"
            >
              <template #reference>
                <el-button type="danger" v-debounced icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="row jcfe">
      <Pagination
        :currenpage="currenpage"
        :count="pesticides.length"
        @prev="onPrevPage"
        @next="onNextPage"
      ></Pagination>
      <!-- <el-tooltip content="上一页"></el-tooltip> -->
      <!-- <el-link :underline="false" class="mr-1">
        <el-icon><ArrowLeft /></el-icon>
      </el-link>

      <el-link :underline="false" class="mr-1">
        <el-icon><ArrowRight /></el-icon>
      </el-link> -->
      <!-- <el-pagination layout="prev,pager, next" :page-count="2" /> -->
    </div>
    <!-- #endregion -->
    <!-- #region 详细列表 -->
    <el-dialog title="详细列表" v-model="DetailVisible" width="60%">
      <el-descriptions border :title="pesticide.name" :column="2">
        <template v-for="(value, key) in pesticide">
          <template v-if="key == 'instructions'"> </template>
          <el-descriptions-item v-else :label="$t(key)">
            {{ value }}
          </el-descriptions-item>
        </template>
      </el-descriptions>
      <el-descriptions border title="产品说明" class="mt-1" :column="1">
        <template v-for="(value, key) in pesticide.instructions">
          <el-descriptions-item
            :label="$t(key)"
            label-class-name="descriptions-item-label"
          >
            <!-- <template #label>{{ $t(key) }}</template> -->
            {{ value }}</el-descriptions-item
          >
        </template>
      </el-descriptions>
    </el-dialog>
    <!-- #endregion -->

    <!-- #region 添加 修改对话框 -->
    <el-dialog
      v-model="AddFromVisible"
      :title="dialogTitle"
      :close-on-click-modal="false"
      width="60%"
    >
      <el-form
        ref="pesticideRef"
        class="pesticide-form"
        :model="pesticide"
        :rules="rules"
        label-width="10em"
      >
        <template v-for="(value, key) in pesticide" :key="key">
          <el-form-item
            v-if="key == 'pesticideRegistrationType'"
            :label="$t(key)"
            :prop="key"
          >
            <el-select v-model="pesticide[key]" style="width: 100%">
              <!-- <el-option :value="1" label="PD" />
              <el-option :value="2" label="WP" />
              <el-option :value="3" label="临时登记证" /> -->
              <el-option
                v-for="(value, index) in pesticideRegistrationType"
                :key="index"
                :value="index + 1"
                :label="value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-else-if="key == 'category'"
            :label="$t(key)"
            :prop="key"
          >
            <el-select v-model="pesticide[key]" style="width: 100%">
              <el-option
                v-for="(value, index) in categories"
                :key="index"
                :label="value"
                :value="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 剂型 -->
          <el-form-item
            v-else-if="key == 'dosageForm'"
            :label="$t(key)"
            :prop="key"
          >
            <el-select v-model="pesticide.dosageForm" style="width: 100%">
              <el-option
                v-for="(value, index) in dosageForms"
                :key="index"
                :value="index"
                :label="value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 保修期 -->
          <el-form-item
            v-else-if="key == 'warrantyPeriod'"
            :prop="key"
            :label="$t(key)"
          >
            <el-input-number v-model="warrantyPeriodNumber" :min="1" :max="5" />
            <span class="ml-1"> 年 </span>
          </el-form-item>
          <template v-else-if="key == 'productionType'">
            <el-form-item prop="productionType" :label="$t('productionType')">
              <el-select v-model="pesticide[key]" class="w100">
                <el-option
                  v-for="(value, index) in productionTypes"
                  :key="index"
                  :label="value"
                  :value="index + 1"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>
          <template v-else-if="key == 'instructions'">
            <template
              v-for="(value2, key2) in pesticide.instructions"
              :key="key2"
            >
              <el-form-item
                :label="$t(key2)"
                :prop="`${key}.${key2}`"
                class="textarea"
              >
                <el-select
                  v-if="key2 == 'toxicityIdentification'"
                  v-model="pesticide.instructions[key2]"
                  class="w100"
                >
                  <el-option
                    v-for="(value, index) in toxicities"
                    :key="index"
                    :label="value"
                    :value="index"
                  >
                  </el-option>
                </el-select>
                <el-input
                  v-else
                  v-model="pesticide.instructions[key2]"
                  :rows="3"
                  autosize
                  type="textarea"
                  class="textarea"
                />
              </el-form-item>
            </template>
          </template>
          <template v-else-if="/id|createTime/.test(key)" />
          <el-form-item v-else :label="$t(key)" :prop="key">
            <el-input v-model="pesticide[key]" clearable />
          </el-form-item>
        </template>
      </el-form>

      <!-- <el-form
        ref="addProductFormRef"
        label-width="8em"
        status-icon
        :rules="rules"
        :model="instructions"
      >
        <template
          v-for="(value, key) in instructions"
          :key="key"
        >
          <el-form-item
            :label="$t(key)"
            :prop="key"
          >
            <el-input
              v-if="key == 'toxicityIdentification'"
              v-model="instructions[key]"
            />
            <el-input
              v-else
              v-model="instructions[key]"
              :rows="3"
              autosize
              type="textarea"
            />
          </el-form-item>
        </template>
      </el-form> -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="AddFromVisible = false">
            {{ $t('Cancel') }}</el-button
          >
          <el-button @click="onPreview">预览</el-button>
          <el-button type="primary" @click="onSubmit" v-debounced>{{
            $t('Confirm')
          }}</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- #endregion -->
  </div>
</template>

<script lang="ts" setup>
/* eslint-disable max-len */
import { Plus } from '@element-plus/icons-vue';
import { ref } from 'vue';
import { rules } from '@/libs/Rules';
import { ElLoading, FormInstance } from 'element-plus';
import { inject } from 'vue';
import { shios } from '@/api/Shios';
import { useStoreRef } from '@/store/useStoreRef';
import {
  toxicities,
  categories,
  productionTypes,
  pesticideRegistrationType,
  dosageForms,
} from '@/store';
import router from '@/route';
import { useRoute } from 'vue-router';

const dialogTitle = ref('添加产品');
const reload = inject<Function>('reload');

const pesticide = ref<Pesticide>({
  createTime: '2023-10-10T16:51:42.424Z',
  id: 0,
  name: '',
  category: 0,
  pesticideRegistrationType: 1,
  registrationNumber: '',
  productionType: 1,
  productionLicenseNumber: '',
  productStandardNumber: '',
  dosageForm: 0,
  entrusterEnterprise: '',
  entrustedEnterprise: '',
  warrantyPeriod: '',
  tel: '',
  netContent: '',
  totalContent: '',
  activeIngredient1: '',
  activeIngredientContent1: '',
  activeIngredient2: '',
  activeIngredientContent2: '',
  activeIngredient3: '',
  activeIngredientContent3: '',
  address: '',
  registeredAddress: '',
  effectiveDate: '',
  // productionBatch: '',
  instructions: {
    features: '',
    scopeAndMethodOfUse: '',
    technicalRequirementsForUse: '',
    mattersNeedAttention: '',
    firstAidMeasuresForPoisoning: '',
    storageAndTransportationMethods: '',
    toxicityIdentification: 1,
    notes: '',
  },
});
const localPesticide = useStoreRef<Pesticide>('localPesticide');
// 保持期
const warrantyPeriodNumber = ref(2);

const pesticideRef = ref<FormInstance>();
// #region 分页
const currenpage = ref(0);
const pagination = [
  {
    first: 0,
    last: 0,
  },
];

// #endregion
const loading = ref(true);
loading.value = true;
const pesticides = ref<Pesticide[]>([]);

pesticides.value = (await getPesticides()) ?? [];

const AddFromVisible = ref(false);
const DetailVisible = ref(false);

/**
 * 提交表单
 */
async function onSubmit() {
  // console.log(JSON.stringify(pesticide));
  pesticide.value.warrantyPeriod = year[warrantyPeriodNumber.value - 1] + '年';
  console.log(pesticide.value);

  await pesticideRef.value?.validate();
  const loadingInstance = ElLoading.service({ fullscreen: true });

  if (dialogTitle.value == '修改产品') {
    const res = await shios.put('Pesticides', {
      path: pesticide.value.id,
      data: pesticide.value,
    });
  } else {
    pesticide.value.createTime = undefined;
    const res = await shios.post('Pesticides', { data: pesticide.value });
    console.log(res);
  }
  // localStorage.setItem('pesticide', JSON.stringify(pesticide.value));
  localPesticide.value = pesticide.value;
  loadingInstance.close();
  reload && reload();
}
async function onDetail(row: Pesticide) {
  const res = await shios.get<Pesticide>(`Pesticides/${row.id}`);

  if (res.data) {
    pesticide.value = res.data;
    console.log(res.data);

    DetailVisible.value = true;
  }
}
/**
 * 复制产品
 * @param row
 */
async function onCopy(row: Pesticide) {
  const res = await shios.get<Pesticide>(`Pesticides/${row.id}`);
  if (res.data) {
    // pesticide.value = res.data;
    Object.assign(pesticide.value, res.data);
    dialogTitle.value = '添加产品';
    pesticide.value.id = 0;
    AddFromVisible.value = true;
  }

  // row.id = 0;
  // row.name += '-复制';
  //const res = await shios.post<Pesticide>('Pesticides', { data: row });
  //console.log(res);
  //reload && reload();
}
/**
 * 添加产品
 */
function onAdd() {
  dialogTitle.value = '添加产品';
  // let localPesticide = localStorage.getItem('pesticide');
  // if (localPesticide) {
  //   pesticide.value = JSON.parse(localPesticide);
  // }
  if (localPesticide.value) {
    pesticide.value = localPesticide.value;
  }
  console.log(pesticide.value);

  pesticide.value.id = 0;
  AddFromVisible.value = true;
}
/**
 *
 * @param {Record<string, any>}row
 */
async function onEdit(row: Record<string, any>) {
  const res = await shios.get<Pesticide>(`Pesticides/${row.id}`);
  if (res.data) {
    pesticide.value = res.data;
  }
  dialogTitle.value = '修改产品';
  AddFromVisible.value = true;
}
/**
 * 删除产品
 * @param {number} id 产品id
 */
async function onDelete(id: number) {
  console.log(id);
  const res = await shios.delete('Pesticides', { path: id });
  console.log(res);
  reload && reload();
}
const year = ['一', '二', '三', '四', '五'];
// /**
//  * 保质期变化
//  * @param value
//  */
// function handleWarrantyPeriodNumberChange() {
//   pesticide.value.warrantyPeriod = year[warrantyPeriodNumber.value - 1] + '年';
// }
// #region 分页

/**
 *
 */
async function onPrevPage() {
  pesticides.value = await getPesticides(
    pagination[currenpage.value - 1].first
  );
  pagination.pop();
  currenpage.value--;
}
async function onNextPage() {
  pagination[currenpage.value].first = pesticides.value[0].id + 1;
  pagination[currenpage.value].last =
    pesticides.value[pesticides.value.length - 1]?.id ?? 0;
  pesticides.value = await getPesticides(pagination[currenpage.value].last);

  currenpage.value++;

  pagination.push({
    first: pesticides.value[0].id + 1,
    last: pesticides.value[pesticides.value.length - 1]?.id ?? 0,
  });
}

// #endregion
/**
 * 获取产品列表
 * @param lastid
 */
async function getPesticides(lastid: number = 0): Promise<Pesticide[]> {
  const data = (
    await shios.get<Pesticide[]>('pesticides', {
      query: { lastid },
    })
  ).data;
  loading.value = false;
  return data;
}
const route = useRoute();

function onPreview() {
  localStorage.setItem('previewPesticide', JSON.stringify(pesticide.value));
  // let href = router.resolve({ path: 'pesicideinfo/details' }).href;
  window.open(router.resolve({ path: 'pesicideinfo/details' }).href);
}
</script>
<style lang="scss" scoped>
.pesticide-form {
  margin: auto;
  display: flex;
  flex-wrap: wrap;

  .el-form-item {
    width: 50%;

    &.textarea {
      width: 100%;
    }
  }

  // grid-template-columns: 1fr 1fr;
}
</style>
